package com.webchat.netty.server.rocketmq.producer;

import com.webchat.netty.server.config.RocketMQResource;
import org.apache.rocketmq.client.producer.MessageQueueSelector;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.common.message.MessageQueue;

import java.util.List;

public class RocketMQProducer {

    /**
     * 普通队列消息发送
     *
     * @param topic
     * @param msg
     * @return
     * @throws Exception
     */
    public static SendResult send(String topic, String msg) throws Exception {

        return send(topic, "", msg);
    }

    public static SendResult send(String topic, String tag, String msg) throws Exception {

        Message message = new Message(topic, tag, msg.getBytes());
        return RocketMQResource.getProducer().send(message, new MessageQueueSelector() {
            @Override
            public MessageQueue select(List<MessageQueue> mqs, Message msg, Object arg) {
                // 错误示例：直接使用 arg 作为 queueId，可能越界
                int queueId = (int) arg;  // 如果 arg=4 会越界
                // 正确做法：取模运算
                return mqs.get(queueId % mqs.size());
            }
        }, 2);
    }
}
